﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;
using System.Web.Http.Controllers;
using System.Web.Helpers;
using System.Threading;
using System.Threading.Tasks;

using MiniSched.Web.Abstractions;

namespace MiniSched.Web.Areas.Api.Filters {
    
    public class ValidateAntiForgeryTokenAttribute : AuthorizationFilterAttribute {

        internal AntiForgeryAbstraction AntiForgeryAbstraction {
            get {
                if (null == _AntiForgeryAbstraction) _AntiForgeryAbstraction = AntiForgeryAbstraction.Default;
                return _AntiForgeryAbstraction;
            }
            set {
                if (null == value) throw new ArgumentNullException("AntiForgeryAbstraction");
                _AntiForgeryAbstraction = value;
            }
        }
        private AntiForgeryAbstraction _AntiForgeryAbstraction;

        public string HeaderTokenName {
            get { return _HeaderTokenName; }
            set { _HeaderTokenName = value; }
        }
        private string _HeaderTokenName = AntiForgeryConfig.CookieName;

        public string CookieTokenName {
            get { return _CookieTokenName; }
            set { _CookieTokenName = value; }
        }
        private string _CookieTokenName = AntiForgeryConfig.CookieName;

        public override void OnAuthorization(HttpActionContext actionContext) {
            var headers = actionContext.Request.Headers;

            var cookie = headers
                .GetCookies()
                .Select(c => c[CookieTokenName])
                .FirstOrDefault();
            var cookieValue = cookie == null ? null : cookie.Value;

            var headerValue = default(string);
            var headerValues = default(IEnumerable<string>);
            if (headers.TryGetValues(HeaderTokenName, out headerValues)) {
                headerValue = headerValues.FirstOrDefault();
            }

            AntiForgeryAbstraction.Validate(cookieValue, headerValue);

            base.OnAuthorization(actionContext);
        }
    }
}
